package com.springboot.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.springboot.domain.Category;
import com.springboot.dto.req.CategoryQueryRequestDTO;
import com.springboot.dto.req.CategorySaveRequestDTO;
import com.springboot.dto.resp.CategoryResponseDTO;
import com.springboot.dto.resp.PageResponse;
import com.springboot.dto.resp.Result;
import com.springboot.service.CategoryService;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {

    @Resource
    private CategoryService categoryService;

    //查询所有分类
    @GetMapping("selectByPage")
    public Result<PageResponse<CategoryResponseDTO>> list(@Valid CategoryQueryRequestDTO categoryQueryRequestDTO) {

        // 查询条件
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        //排序
        queryWrapper.orderByAsc("sort");

        //分页
        Page<Category> page = new Page<>(categoryQueryRequestDTO.getPage(), categoryQueryRequestDTO.getSize());
        Page<Category> categoryPage = categoryService.page(page, queryWrapper);

        //日志输出总记录数和总页数
        log.info("总记录数:{},总页数:{}", categoryPage.getTotal(), categoryPage.getPages());

        // 转换成DTO
        PageResponse<CategoryResponseDTO> pageResponse = new PageResponse<>();
        List<CategoryResponseDTO> categoryResponseDTOS = BeanUtil.copyToList(categoryPage.getRecords(), CategoryResponseDTO.class);

        // 封装分页信息
        pageResponse.setTotal(categoryPage.getTotal());
        pageResponse.setList(categoryResponseDTOS);

        // 返回
        return Result.success(pageResponse);
    }

    // 新增
    @PostMapping
    public Result<String> save(@Valid @RequestBody CategorySaveRequestDTO categorySaveRequestDTO) {

        Category category = BeanUtil.copyProperties(categorySaveRequestDTO, Category.class);

        categoryService.saveOrUpdate(category);

        return Result.success("保存或更新成功");
    }


    // 删除
    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable("id") Long id) {
        categoryService.removeById(id);
        return Result.success();
    }

}
